import React from 'react';
import { Modal, message } from 'antd';
import Api from 'Utils/api';
import { WEBRTC_APPID } from 'Constants/config';
import './video.scss';


export default class OnVideoModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      isRecording: true,
      loading: false,
      isUsingPlugin: true,
      againRecord: true,
      recordUrl: ''
    };
    this.handleStart = ::this.handleStart;
    this.handleStop = ::this.handleStop;
    this.handleVideo = ::this.handleVideo;
    this.initUserInfo = ::this.initUserInfo;
    this.connectChannel = ::this.connectChannel;
    this.changeBtnState = ::this.changeBtnState;
  }
  showModal() {
    this.setState({
      visible: true,
      loading: false,
      isRecording: true,
      againRecord: false,
      recordUrl: ''
    }, () => {
      const self = this;
      AdapterJS.webRTCReady((isUsingPlugin) => {
        self.setState({
          isUsingPlugin
        });
      });
      this.initUserInfo();
    });
  }

  initUserInfo() {
    const api = new Api({
      method: 'POST',
      path: '/login/guest',
      success: (res) => {
        this.setState({
          userInfo: res
        }, () => {
          this.websocketConnect(res);
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  websocketConnect(userInfo) {
    const socket = new SockJS(`${window.config.API_HOST}/gs-guide-websocket?socket_auth=${userInfo.socket_auth}`);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, () => {
      this.stompClient.subscribe(`/topic/guest.${userInfo.id}/chat`, (res) => {
        const json = JSON.parse(res.body);
        console.log('json', json);
        // 录制
        if (json.type === 'initRecordingRes') {
          this.setState({
            channelKey: json.channelKey,
            chatId: json.chatId,
            againRecord: true
          });
         // this.connectChannel(json.channelKey, json.chatId);
        }
        // 结束录制
        if (json.type === 'record_success') {
          this.setState({
            recordUrl: json.id,
            againRecord: true,
            loading: false,
          });
        }
      });
      this.stompClient.send('/app/recording/req', {}, JSON.stringify({ audioOnly: false }));
    });
  }
  connectChannel(channelkey, chatId) {
    console.log('connectChannel', channelkey, chatId, this.state.userInfo.id);
    this.client = AgoraRTC.createClient({ mode: 'interop' });
    this.client.init(WEBRTC_APPID,
      () => {
        //加入 AgoraRTC 频道(join)
        this.client.join(channelkey, chatId, this.state.userInfo.id,
          () => {
            //创建音视频对象
            this.localStream = AgoraRTC.createStream({
              streamID: parseInt(this.state.userInfo.id, 10),
              audio: true,
              video: true,
              screen: false,
            });
            // 初始化音视频流对象
            this.localStream.init(() => {
              // 播放本地视频流
              window.stream = this.localStream.stream;
              console.log('enter');
              if (this.state.isUsingPlugin) {
                AdapterJS.attachMediaStream(document.getElementById('video'), window.stream);
              } else {
                this.localStream.play('video', '/images');
              }
              console.log('end');
              // 将本地的视频流上传到服务器
              this.client.publish(this.localStream, (err) => {
                console.log('publish is err', err);
              });
              // start record
              console.log('enterChannel');
              this.stompClient.send('/app/recording/start', {},
                JSON.stringify({ chatId: chatId, audioOnly: false }));
            }, () => {
              // console.log(err);
            });
          },
          () => {});
      },
      (err) => { console.log(err); });
  }
  handOk() {
    const { recordUrl, againRecord, isRecording } = this.state;
    const { onOk } = this.props;
    if (!isRecording) {
      message.warn('请停止录制!', 3);
      return;
    }
    if (!recordUrl && againRecord) {
      return;
    }
    this.setState({
      visible: false,
    }, onOk && onOk(recordUrl));

    /* const { onOk } = this.props;
     this.setState({ loading: true });
     this.recorder.getMp3Blob((blob) => {
       mp3Blob = blob;
       const file = new File([mp3Blob], `${(new Date()).toISOString().replace(/:|\./g, '-')}.mp3`, { type: 'audio/webm' });
       const formData = new FormData();
       formData.append('upload_file', file, file.name);
       const api = new Api({
         method: 'POST',
         path: '/files',
         noHeader: true,
         data: formData,
         success: (res) => {
           this.setState({
             visible: false,
             loading: false,
           }, onOk && onOk(res.id));
         },
         error: () => {
           this.setState({ loading: false });
         }
       });
       api.run();
     });*/
  }

  close() {
    this.setState({
      visible: false,
    });
  }
  handleStart() {
    console.log('start');
    const { channelKey, chatId } = this.state;
    console.log(this.state.channelKey, this.state.chatId);
    if (channelKey && chatId) {
      this.connectChannel(this.state.channelKey, this.state.chatId);
    }
  }
  handleStop() {
    this.client.leave((success) => { console.log(success); }, (err) => { console.log(err); });
    console.log('leave');
    this.client.unpublish(this.localStream);
    this.localStream.close();
    if (this.state.isUsingPlugin) {
      AdapterJS.attachMediaStream(document.getElementById('video'), null);
    } else {
      this.localStream.stop();
    }
    console.log('end');
  }
  handleVideo() {
    const { againRecord, isRecording } = this.state;
    if (againRecord) {
      if (isRecording) {
        this.handleStart();
      } else {
        this.handleStop();
        this.setState({
          againRecord: false,
          loading: true,
        });
      }
      this.changeBtnState();
    }
  }
  changeBtnState() {
    this.setState(preState => ({
      isRecording: !preState.isRecording
    }));
  }
  render() {
    const { isUsingPlugin, isRecording } = this.state;
    const btnImg = isRecording ? 'icon_audio_record.png' : 'icon_audio_pause.png';
    return (
      <Modal
        className="add-video-modal"
        title="录制视频"
        visible={this.state.visible}
        onOk={this.handOk.bind(this)}
        onCancel={() => {
          this.close();
        }}
        confirmLoading={this.state.loading}
        maskClosable={false}
      >
        <div className="modal-video-wrap">
          {
            isUsingPlugin ? <video className="modal-video" id="video" style={{ width: '100%', height: '100%', backgroundColor: 'black' }} />
              : <div id="video" className="modal-div" style={{ width: '100%', height: '100%', backgroundColor: 'black' }} />
          }
          <img src={`images/icons/${btnImg}`} alt="录制视频" className="modal-video-imgs" onClick={this.handleVideo.bind(this)} />
        </div >
      </Modal >
    );
  }
}
